package com.yunyun400.vosk.service;

import java.util.Properties;

import javax.mail.AuthenticationFailedException;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.yunyun400.vosk.entity.ReminderRecord;

/**
 * 邮件通知服务
 * 负责将提醒消息通过邮件推送到指定邮箱
 */
@Service
public class EmailNotificationService {
    
    private static final Logger logger = LoggerFactory.getLogger(EmailNotificationService.class);
    
    // 邮件服务器配置
    @Value("${email.smtp.host:smtp.163.com}")
    private String smtpHost;
    
    @Value("${email.smtp.port:465}")  // Changed to 465 for SSL
    private int smtpPort;
    
    @Value("${email.smtp.auth:true}")
    private boolean smtpAuth;
    
    @Value("${email.smtp.ssl.enable:true}")  // Changed to true for 163.com
    private boolean smtpSslEnable;
    
    // 发件人配置
    @Value("${email.from:cuiweijun08@163.com}")
    private String fromEmail;
    
    @Value("${email.password:}")
    private String emailPassword;
    
    // 收件人配置
    @Value("${email.to:cuiweijun08@163.com}")
    private String toEmail;
    
    // 是否启用邮件通知
    @Value("${email.notification.enabled:true}")
    private boolean enabled;
    
    /**
     * 发送提醒邮件
     * @param reminder 提醒记录
     * @return 是否发送成功
     */
    public boolean sendReminderEmail(ReminderRecord reminder) {
        // 检查是否启用邮件通知
        if (!enabled) {
            logger.info("邮件通知未启用，跳过发送");
            return false;
        }
        
        // 检查必要的配置是否存在
        if (emailPassword == null || emailPassword.isEmpty()) {
            logger.error("邮箱密码未配置，请在application.properties中设置email.password");
            return false;
        }
        
        try {
            // 创建邮件会话
            Properties props = new Properties();
            props.put("mail.smtp.host", smtpHost);
            props.put("mail.smtp.port", smtpPort);
            props.put("mail.smtp.auth", smtpAuth);
            
            if (smtpSslEnable) {
                props.put("mail.smtp.ssl.enable", "true");
                props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                props.put("mail.smtp.socketFactory.port", smtpPort);
            }
            
            // 启用调试模式以便更好地排查问题
            props.put("mail.debug", "false");
            
            // 创建会话对象
            Session session = Session.getInstance(props);
            
            // 创建邮件消息
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(fromEmail));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
            
            // 设置邮件主题和内容
            message.setSubject("【重要】发现含有关键词的录音文件");
            message.setContent(buildEmailContent(reminder), "text/html; charset=UTF-8");
            
            // 发送邮件
            Transport transport = session.getTransport("smtp");
            transport.connect(fromEmail, emailPassword);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
            
            logger.info("邮件已成功发送到: {}, 提醒ID: {}", toEmail, reminder.getId());
            return true;
        } catch (AuthenticationFailedException e) {
            logger.error("邮件认证失败，请确保：1. SMTP服务已开启 2. 使用的是正确的授权码而非登录密码", e);
            logger.warn("请在163邮箱设置中开启SMTP服务，并生成专用授权码，而非使用登录密码");
            return false;
        } catch (AddressException e) {
            logger.error("邮件地址格式错误", e);
            return false;
        } catch (MessagingException e) {
            logger.error("邮件发送失败: " + e.getMessage(), e);
            return false;
        } catch (Exception e) {
            logger.error("发送邮件时发生未知错误", e);
            return false;
        }
    }
    
    /**
     * 构建邮件内容
     * @param reminder 提醒记录
     * @return HTML格式的邮件内容
     */
    private String buildEmailContent(ReminderRecord reminder) {
        StringBuilder content = new StringBuilder();
        content.append("<html><body>");
        content.append("<h2>【重要】发现含有关键词的录音文件</h2>");
        content.append("<table border='1' cellpadding='5' cellspacing='0' style='border-collapse: collapse;'>");
        content.append("<tr><td style='background-color: #f0f0f0; font-weight: bold;'>文件名称</td><td>")
               .append(reminder.getRecordingFileName()).append("</td></tr>");
        content.append("<tr><td style='background-color: #f0f0f0; font-weight: bold;'>检测时间</td><td>")
               .append(reminder.getDetectionTime()).append("</td></tr>");
        content.append("<tr><td style='background-color: #f0f0f0; font-weight: bold;'>批次ID</td><td>")
               .append(reminder.getBatchId()).append("</td></tr>");
        content.append("<tr><td style='background-color: #f0f0f0; font-weight: bold;'>文件列表</td><td>")
               .append(reminder.getRecords()).append("</td></tr>");
        
        if (reminder.getRecognizedText() != null) {
            content.append("<tr><td style='background-color: #f0f0f0; font-weight: bold;'>识别内容</td><td>")
                   .append(reminder.getRecognizedText()).append("</td></tr>");
        }
        
        content.append("</table>");
        content.append("<p style='color: #ff0000; font-weight: bold;'>请及时处理相关提醒！</p>");
        content.append("</body></html>");
        
        return content.toString();
    }
    
    /**
     * 批量发送提醒邮件
     * @param reminders 提醒记录列表
     * @return 成功发送的数量
     */
    public int sendBatchReminders(java.util.List<ReminderRecord> reminders) {
        int successCount = 0;
        for (ReminderRecord reminder : reminders) {
            if (sendReminderEmail(reminder)) {
                successCount++;
            }
        }
        return successCount;
    }
}